package com.yijiu.trb;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.yijiu.action.BaseAction;
import com.yijiu.adapter.ScrollFootListener;
import com.yijiu.adapter.SuggestProjectAdapter;
import com.yijiu.network.Const;
import com.yijiu.network.Request;
import com.yijiu.network.StringUtils;
import com.yijiu.resource.ActionType;
import com.yijiu.resource.C;
import com.yijiu.resource.CacheData;
import com.yijiu.resource.Project;
import com.yijiu.response.ProjectResponse;
import com.yijiu.response.RequestAccountInfoResponse;
import com.yijiu.response.RequestPersonalInfoResponse;
import com.yijiu.utils.DialogUtils;

/**
 * 推荐项目
 * 
 * @author TangChao
 */
public class SuggestProjectActivity extends BTitleWithUserinfoActivity implements ScrollFootListener, OnItemClickListener
{

	/**
	 * 列表
	 */
	private ListView listView;

	/**
	 * 适配器
	 */
	private SuggestProjectAdapter suggestProjectAdapter;

	private int pageIndex = 1;

	private boolean isLoadOver, onFoot = false;

	private String type = null;

	private String timeStart = null;

	private String timeEnd = null;

	private String tradeType = "0";

	public static SuggestProjectActivity instance = null;

	private long exitTime = 0;

	private Handler handler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case 1:
					if (msg.arg1 == 0)
					{
						tradeType = "0";
					}
					else if (msg.arg1 == 1)
					{
						tradeType = "1";
					}
					else if (msg.arg1 == 2)
					{
						tradeType = "2";
					}
					timeStart = null;
					timeEnd = null;
					type = null;
					break;
				case 2:
					if (msg.arg1 == 0)
					{
						timeStart = "1";
						timeEnd = "3";
					}
					else if (msg.arg1 == 1)
					{
						timeStart = "3";
						timeEnd = "6";
					}
					else if (msg.arg1 == 2)
					{
						timeStart = "6";
						timeEnd = "9";
					}
					else if (msg.arg1 == 3)
					{
						timeStart = "9";
						timeEnd = "12";
					}
					type = null;
					break;
				case 3:
					type = msg.arg1 == 0 ? "YT" : "EDU";
					timeStart = null;
					timeEnd = null;
					break;
			}
			pageIndex = 1;
			onFoot = false;
			requestProjectList(pageIndex, onFoot);
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.main_layout);
		initWidget();
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		requestProjectList(pageIndex, false);
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();
		requestProjectList(pageIndex, false);
	}

	/**
	 * 初始化控件
	 */
	public void initWidget()
	{
		instance = this;
		listView = (ListView) findViewById(R.id.main_layout_list_view);
		listView.setOnItemClickListener(this);
		requestProjectList(pageIndex, onFoot);
	}

	/**
	 * 个人信息请求
	 * 
	 * @param appKey
	 */
	private void requestPersonInfo(String appKey)
	{
		String inputStr = "service=personalInfoService";
		encryptBase(inputStr, C.PRIVATE_KEY);
		BaseAction action = new BaseAction(encodedData, encriptData, appKey);
		RequestPersonalInfoResponse requestPersonalInfo = new RequestPersonalInfoResponse();
		Request request = new Request(action, requestPersonalInfo, ActionType.REQUEST_PERSONAL_INFO);
		netManager.excute(request, this, this);
		showProgress("正在获取数据");
	}

	/**
	 * 按钮点击事件
	 * 
	 * @param v
	 */
	public void suggestProjectClick(View v)
	{
		int id = v.getId();
		switch (id)
		{
			case R.id.tv_main_jindu:
				String[] jindu =
				{
						"全部", "待成立", "已成立"
				};
				DialogUtils.showFilterDialog(this, jindu, 1, handler);
				break;
			case R.id.tv_main_qixian:
				String[] qixian =
				{
						"1~3月期", "3~6月期", "6~9月期", "9~12月期"
				};
				DialogUtils.showFilterDialog(this, qixian, 2, handler);
				break;
			case R.id.tv_main_gongsi:
				String[] gongsi =
				{
						"渝台担保", "教育担保"
				};
				DialogUtils.showFilterDialog(this, gongsi, 3, handler);
				break;
			default:
				break;
		}
	}

	@Override
	public void onFoot()
	{
		if (isLoadOver)
		{
			return;
		}
		onFoot = true;
		requestProjectList(++pageIndex, onFoot);
	}

	/**
	 * 请求项目列表
	 */
	private void requestProjectList(int pageIndex, boolean onFoot)
	{
		// 将用户输入的信息拼接成字符串发送到服务器
		StringBuffer sb = new StringBuffer();
		sb.append("service=indexTrade");
		sb.append("&pageSize=10&pageNo=" + pageIndex);
		if (!StringUtils.isNull(type))
		{
			sb.append("&guarantee=" + type);
		}
		if (!StringUtils.isNull(timeStart) && !StringUtils.isNull(timeEnd))
		{
			sb.append("&timeUnit=M&startTime=" + timeStart + "&endTime=" + timeEnd);
		}
		if (!StringUtils.isNull(tradeType))
		{
			sb.append("&tradeType=" + tradeType);
		}
		String inputStr = sb.toString();
		encryptBase(inputStr, C.PRIVATE_KEY);
		BaseAction requestData = new BaseAction(encodedData, encriptData);
		// 响应
		ProjectResponse projectResponse = new ProjectResponse();
		// 请求服务器
		Request request = new Request(requestData, projectResponse, ActionType.REQUEST_DATA);
		netManager.excute(request, this, this);
		if (onFoot)
		{
			suggestProjectAdapter.showprogress();
		}
		else
		{
			showProgress("正在获取投资项目数据，请稍候");
		}
	}

	/* 操作成功返回的函数 */
	@Override
	public void getResult(Request r)
	{
		super.getResult(r);
		switch (r.getType())
		{
			case ActionType.REQUEST_DATA:
				if (onFoot)
				{
					suggestProjectAdapter.hideprogress();
				}
				ProjectResponse projectResponse = (ProjectResponse) r.getResponse();
				if (projectResponse.projectList == null || projectResponse.projectList.isEmpty()
						|| projectResponse.projectList.size() < 10)
				{
					isLoadOver = true;
				}
				else
				{
					isLoadOver = false;
				}
				if (suggestProjectAdapter == null || pageIndex == 1)
				{
					suggestProjectAdapter = new SuggestProjectAdapter(this, projectResponse.projectList);
					suggestProjectAdapter.setScrollFootListener(this);
					listView.setAdapter(suggestProjectAdapter);
				}
				else
				{
					if (projectResponse.projectList != null && !projectResponse.projectList.isEmpty())
					{
						suggestProjectAdapter.addAll(projectResponse.projectList);
					}
				}
				setTitleInfoVisibility();
				if (!CacheData.APP_KEY.equals(""))
				{
					refresh();
				}
				break;
			case ActionType.REQUEST_ACCOUNT_INFO:// 请求账户信息
				RequestAccountInfoResponse itemAccountInfoResponse = (RequestAccountInfoResponse) r.getResponse();
				CacheData.AVAILABLE_BALANCE = itemAccountInfoResponse.field.availableBalance + "";
				requestPersonInfo(CacheData.APP_KEY);
				break;
			case ActionType.REQUEST_PERSONAL_INFO:// 请求个人信息
				RequestPersonalInfoResponse itemPersonalInfoResponse = (RequestPersonalInfoResponse) r.getResponse();
				CacheData.BANK_CARD_NAME = itemPersonalInfoResponse.field.bankName;
				CacheData.BANK_CARD_NUMBER = itemPersonalInfoResponse.field.bankCardNo;
				CacheData.REAL_NAME_STATUS = itemPersonalInfoResponse.field.realNameStatus;
				CacheData.BANK_ICON_URL = itemPersonalInfoResponse.field.banklog;
				showPersonalInfo(CacheData.REAL_NAME,
						(CacheData.AVAILABLE_BALANCE == null || "null".equals(CacheData.AVAILABLE_BALANCE) ? "0.0"
								: CacheData.AVAILABLE_BALANCE));
				break;
		}
	}

	/* 操作失败返回的函数 */
	@Override
	public void notifyError(int type, int errorCode, String errorMsg)
	{
		super.notifyError(type, errorCode, errorMsg);
		switch (type)
		{
			case ActionType.REQUEST_DATA:
				if (Const.NO_NETWORK == errorCode)
				{
					setTitleInfoInVisibility();
					return;
				}
				app.showMsg(errorMsg);
				break;
			case ActionType.REQUEST_ACCOUNT_INFO:
			case ActionType.REQUEST_PERSONAL_INFO:
				app.showMsg(errorMsg);
				break;
		}
	}

	/* 重复提交返回的函数 */
	@Override
	public void rePost(Request r)
	{
		super.rePost(r);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
	{
		Project project = (Project) arg0.getItemAtPosition(arg2);
		Intent intent = new Intent(this, ProjectDetailsActivity.class);
		try
		{
			intent.putExtra("tradeId", String.valueOf(project.tradeId));
			intent.putExtra("demandId", String.valueOf(project.demandId));
			int statusNum = project.tradeStatus;
			String str = null;
			if (statusNum == 1)
			{
				str = "截止时间：";
			}
			else if (statusNum == 2)
			{
				str = "成立时间：";
			}
			else if (statusNum == 3 || statusNum == 7)
			{
				str = "还款时间：";
			}
			else if (statusNum == 6)
			{
				str = "完成时间：";
			}
			else if (statusNum == 8)
			{
				str = "成立时间：";
			}
			intent.putExtra("statusType", String.valueOf(statusNum));
			intent.putExtra("timeType", str);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		startActivity(intent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN)
		{
			if ((System.currentTimeMillis() - exitTime) > 2000)
			{
				Toast.makeText(getApplicationContext(), "再按一次返回键退出程序", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			}
			else
			{
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
